package com.framewiki.example.service;

import com.cdkjframework.datasource.jpa.builder.JpaCriteriaBuilder;
import com.cdkjframework.oauth2.entity.OAuth2Token;
import com.cdkjframework.oauth2.repository.OAuth2TokenRepository;
import com.cdkjframework.util.make.GeneratedValueUtils;
import com.cdkjframework.util.tool.CopyUtils;
import com.framewiki.example.entity.RmsOauth2TokensEntity;
import com.framewiki.example.repository.RmsOauth2TokensRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @ProjectName: framewiki-example
 * @Package: com.framewiki.example.service
 * @ClassName: OAuth2TokenRepositoryImpl
 * @Description: java类作用描述
 * @Author: xiaLin
 * @Date: 2025/8/27 20:56
 * @Version: 1.0
 */
@Service
@RequiredArgsConstructor
public class OAuth2TokenRepositoryImpl implements OAuth2TokenRepository {

  private final RmsOauth2TokensRepository rmsOauth2TokensRepository;

  /**
   * 保存OAuth2令牌
   *
   * @param oAuth2Token OAuth2令牌实体
   */
  @Override
  public void save(OAuth2Token oAuth2Token) {
    RmsOauth2TokensEntity entity = CopyUtils.copyNoNullProperties(oAuth2Token, RmsOauth2TokensEntity.class);
    entity.setId(GeneratedValueUtils.getMonotonicUlidString());
    rmsOauth2TokensRepository.save(entity);
  }

  /**
   * 根据访问令牌查找OAuth2令牌
   *
   * @param refreshToken 访问令牌
   * @return OAuth2令牌实体
   */
  @Override
  public OAuth2Token findByRefreshToken(String refreshToken) {
    JpaCriteriaBuilder<RmsOauth2TokensEntity> builder = JpaCriteriaBuilder.Builder();
    builder.equal("refreshToken", refreshToken);

    Optional<RmsOauth2TokensEntity> optional = rmsOauth2TokensRepository.findOne(builder.build());
    if (optional.isPresent()) {
      return CopyUtils.copyNoNullProperties(optional.orElse(null), OAuth2Token.class);
    } else {
      return null;
    }
  }
}
